package com.faker.core.generate.common;

import com.faker.core.generate.data.DataGenerator;

import java.util.List;
import java.util.Map;

public class SqlGenerate {
    /**
     * 拼接批量插入的insert语句
     *
     * @param tableData
     * @param generationNum
     * @return
     */
    public static String insertSqlStringGen(List<Map<String, Object>> tableData, Integer generationNum) {
        // 拼接批量插入的insert语句
        StringBuffer sqlString = new StringBuffer();

        String tableName = tableData.get(0).get("tableName").toString();
        // SQL语句的insert部分
        StringBuffer insertPart = new StringBuffer();
        insertPart.append("insert into ").append(tableName).append(" ( ");

        // SQL语句的values部分（不包含values关键字）
        StringBuffer valuesPart = new StringBuffer("( ");
        for (Map<String, Object> table : tableData) {
            Object genType = table.get("genType");
            Object genKeyCode = table.get("genKeyCode");
            Object genKeyTable = table.get("genKeyTable");
            Object genKeyGlobal = table.get("genKeyGlobal");
            if (genType != null && (genKeyCode != null || genKeyTable != null || genKeyGlobal != null)) {
                Object columnName = table.get("columnName");
                insertPart.append(columnName);
                insertPart.append(",");
                valuesPart.append("?,");
            }
        }
        //删除最后一个逗号
        insertPart.deleteCharAt(insertPart.length() - 1);
        valuesPart.deleteCharAt(valuesPart.length() - 1);


        insertPart.append(" ) ");
        valuesPart.append(" ) ");

        sqlString.append(insertPart);
        sqlString.append("values");

        //TODO 需要优化：如果生成数量大于100分批次生成
        // 根据生成数量，拼接生成values数量
        for (Integer i = 0; i < generationNum; i++) {
            if (i == 0) {
                sqlString.append(valuesPart);
            } else {
                sqlString.append(",").append(valuesPart);
            }
        }

        return sqlString.toString();
    }


    public static String selectSqlStringGen(String tableName, List<Object> fieldList) {
        StringBuffer sqlString = new StringBuffer();
        sqlString.append(" select ");
        for (int i = 0; i < fieldList.size(); i++) {
            Object field = fieldList.get(i);
            if (i < fieldList.size() - 1) {
                sqlString.append(field.toString());
                sqlString.append(",");
            } else {
                sqlString.append(field);
            }
        }
        sqlString.append(" from ").append(tableName);
        return sqlString.toString();
    }
}
